var basePath = $("#basePath").val();
$(document).ready(function (){
    initElementCss();
    menuCss("新闻");
    queryNewsList(0,100);
    bindEvent();
    initNewsType();
});


function bindEvent(){
        $("#add").click(function (){
            $("#add-modal").iziModal("open",this);
        });

        $("#saveNews").click(function (){
            saveNews(0);
        });

        $("#publisNews").click(function (){
            checkPublisNews(1);
        });

        $("#search").click(function (){
            queryNewsList(0,100);
        });

        $("#edit").click(function (){
            editNewsInit();
        });

        $("#withdraw").click(function (){
            if(!$("input[name='one']:checked").length){
                flavrShowByTime("请选择一个新闻", null, "danger", false);
                return;
            }

            var status = $("input[name='one']:checked").parent().next().val();
            if(status != 1){
                flavrShowByTime("当前新闻不能撤回", null, "danger", false);
                return;
            }

            var newsId = $("input[name='one']:checked").val();
            checkWithdraw(newsId);
        });
}

function queryNewsList(start,end) {
        var startDate = $("#queryForm").find("[name='startDate']").val();
        var endDate = $("#queryForm").find("[name='endDate']").val();
        var title = $("#queryForm").find("[name='title']").val();
        var json = {};
        json.startDate = startDate;
        json.endDate = endDate;
        json.title = title;
        json.start = start;
        json.end = end;

        var url = basePath+"/news/queryNewsList";
        publicAjax(url,"POST",json,function (data){
            if(data.ret == 200){
                bindNewsListData(data.data);
            }else{
                flavrShowByTime(data.msg,null,"danger",false)
            }
        });
}

function bindNewsListData(obj){
        $("#news_table").html("");
        if(obj.list == null || obj.list.length == 0){
            $("#news_table").html("<tr><td class='text-center text-muted' colspan='9'>暂无新闻</td></tr>");
            return;
        }
        var html = "";
        $.each(obj.list,function (index,item){
            var statusStr = "";
            if(item.status == 0){
                statusStr = "草稿 &nbsp;&nbsp;<button type='button' class='btn btn-primary btn-xs' onclick='checkPublisNews("+item.newsId+")' data-original-title='发布'>发布</button>";
            }else if(item.status == 1){
                statusStr = "已发布";
            }else if(item.status == 2){
                statusStr = "已撤回";
            }
                html += "<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
                    "<td class='text-center text-muted'><input type='checkbox' name='one' class='flat-green' value='"+item.newsId+"'><input type='hidden' name='status' value='"+item.status+"'> </td>"+
                    /* "<td class='text-center text-muted'><button type='button' class='btn btn-primary btn-xs' onclick='queryNewsInfo("+item.newsId+")' data-original-title='详情'><i class='fa fa-file-text-o'></i></button></td>" +*/
                    "<td class='text-center text-muted'>"+(item.newsTypeName == null ? '' : item.newsTypeName)+"</td>" +
                    "<td class='text-center text-muted'>"+(item.startTime == null ? '' : item.startTime)+"</td>" +
                    "<td class='text-center text-muted'>"+(item.endTime == null ? '' : item.endTime)+"</td>" +
                  /*  "<td class='text-center text-muted'>"+(item.publishPersonName == null ? '' : item.publishPersonName)+"</td>" +*/
                    "<td class='text-center text-muted'>"+(item.title == null ? '' : item.title)+"</td>" +
                    "<td class='text-center text-muted'><a target='_blank' href='"+item.url+"'>"+(item.url == null || item.url == '' ? '' : '文件查看')+"</a></td>" +
                    "<td class='text-center text-muted'>"+statusStr+"</td>" +
                    "</tr>"
        });
        $("#news_table").html(html);
    initDomCss();
}

function publisNews(id){

        var url = basePath+"/news/publisNews";
        publicAjax(url,"POST",{id:id},function (data) {
            if(data.ret == 200){
                flavrShowByTime(data.msg,null,"success",false);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
        })
}

function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}


function queryNewsInfo(newsId){
    var url = basePath+"/news/info";
    location.href=url+"?newsId="+newsId;
}




function initElementCss(){
    $("#queryForm").find("[name='startDate']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        forceParse: true,
        format: 'yyyy-mm-dd',
        minView: 2,
        todayBtn: true
    });

    $("#queryForm").find("[name='endDate']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        forceParse: true,
        format: 'yyyy-mm-dd',
        minView: 2,
        todayBtn: true
    });


    $("#add-update-from").find("input[name='startTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        forceParse: true,
        format: 'yyyy-mm-dd',
        minView: 2,
        todayBtn: true
    }).on('hide',function(e) {
        $('#add-update-from').data('bootstrapValidator').updateStatus('startTime', 'NOT_VALIDATED',null).validateField('startTime');
    });

    $("#add-update-from").find("input[name='endTime']").datetimepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN',
        forceParse: true,
        format: 'yyyy-mm-dd',
        minView: 2,
        todayBtn: true
    }).on('hide',function(e) {
        $('#add-update-from').data('bootstrapValidator').updateStatus('endTime', 'NOT_VALIDATED',null).validateField('endTime');
    });



}

function initNewsType(){
    var url = basePath+"/base/queryItem";
    $("#add-update-from").find("[name='newsType']").html("");
    publicAjax(url,"POST",{"type":"news_type"},function (data){
        if(data.ret == 200) {
            var html = "";
            $.each(data.data, function (index, item) {
                html += "<option value='" + item.itemId + "'>" + item.item + "</option>";
            })
            $("#add-update-from").find("[name='newsType']").html(html);
            $("#add-update-from").find("[name='newsType']").val(null);
            $("#add-update-from").find("[name='newsType']").select2({
                language: 'zh-CN',
                placeholder: '请选择',
                allowClear: true});

        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }

    })
}


$("#add-modal").iziModal({
    title: "编辑新闻",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1042,
    iframe: false,
    focusInput: false,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: true,
    overlay: true,
    overlayClose: false,
    overlayColor: 'rgba(0, 0, 0, 0.4)',
    onOpening: function () {
        validator();
    },
    onOpened: function () {
    },
    onClosing: function () {
        $('#add-update-from')[0].reset();
        $("#add-update-from").data('bootstrapValidator').destroy();
        $("#add-update-from").find("[name='status']").val("");
        $("#add-update-from").find("[name='newsId']").val("");
        $("#add-update-from").find("[name='newsType']").val(null).trigger("change");
    },
    onClosed: function () {

    }
});


function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            title: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },newsType: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },startTime: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    date: {
                        format: 'YYYY-MM-DD',
                        message: '格式为YYYY-MM-DD'
                    }
                }
            },endTime :{
                validators: {
                    date: {
                        format: 'YYYY-MM-DD',
                        message: '格式为YYYY-MM-DD'
                    }
                }
            }
        }
    });
}

var bl = false;
function saveNews(status){
    if(!getFileName()){
        flavrShowByTime("请上传后缀为zip的压缩包",null,"danger",false);
        return;
    }
    if(($("#startTime").val() == "" && $("#endTime").val()=="") || ($("#startTime").val() > $("#endTime").val())){
        flavrShowByTime("开始时间不能大于结束时间",null,"danger",false);
        return;
    }

    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl ){
            bl = true;
            var url=basePath+"/news/saveNews";
            $('#add-update-from').find("[name='status']").val(status);
            var formData = new FormData($("#add-update-from")[0]);
            $.ajax({
                type : "POST",
                url: url,
                data :formData,//整个表单提交
                dataType : "json",
                async: true,
                cache: false,
                contentType: false,
                processData: false,
                success : function(data) {
                    if(data.ret == 200){
                        flavrShowByTime(data.msg,null,"success",false);
                        $("#add-modal").iziModal("close",this);
                        bl = false;
                        queryNewsList(0,100);
                    }else{
                        flavrShowByTime(data.msg,null,"danger",false);
                        bl= false;
                    }
                }
            });
        }
    }
}


function checkPublisNews(id){
    new $.flavr({
        closeOverlay : true,
        closeEsc : true,
        content : '是否确认发布?',
        buttons:[
            {text:'取消',style:'info',action:function(){

            }},
            {
                text:'发布',
                style:'primary',
                action:function(){
                    publisNews(id);
                }
            }
        ]
    });
}

function  editNewsInit() {
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个新闻", null, "danger", false);
        return;
    }

    var status = $("input[name='one']:checked").parent().next().val();
    if(status > 0){
        flavrShowByTime("当前新闻不能编辑", null, "danger", false);
        return;
    }

    var newsId = $("input[name='one']:checked").val();
    var url = basePath+"/news/queryNewsInfo"
    publicAjax(url,"POST",{newsId:newsId},function (data) {
        if(data.ret == 200){
            bindNewsData(data.data);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}

function bindNewsData(obj){
    $("#add-update-from").find("[name='newsId']").val(obj.newsId);
    $("#add-update-from").find("[name='title']").val(obj.title == null ? '' : obj.title);
    $("#add-update-from").find("[name='publisTime']").val(obj.publisTime == null ? '' : obj.publisTime);
    $("#add-update-from").find("[name='publishContent']").val(obj.publishContent == null ? '' : obj.publishContent);
    $("#add-update-from").find("[name='remark']").val(obj.remark == null ? '' : obj.remark);
    $("#add-update-from").find("[name='newsType']").val(obj.newsType).trigger("change");

    $("#add-modal").iziModal("open",this);
}

function checkWithdraw(newsId){
    new $.flavr({
        closeOverlay : true,
        closeEsc : true,
        content : '是否确认撤回?',
        buttons:[
            {text:'取消',style:'info',action:function(){

            }},
            {
                text:'撤回',
                style:'primary',
                action:function(){
                    withdraw(newsId);
                }
            }
        ]
    });
}

function withdraw(newsId) {
        var url = basePath+"/news/withdraw"
        publicAjax(url,"POST",{newsId:newsId},function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    queryNewsList(0,100);
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
        })
}


function getFileName(){
    var obj = document.getElementById('files');
    if(obj.files[0] != undefined){
        var filevalue = obj.value;
        var index = filevalue.lastIndexOf('.');
        var extensions = filevalue.substring(index+1);
        if(extensions == 'zip'){
            return true;
        }else{
            return false;
        }
    }else{
        return true;
    }
}



$('input[name=files]').fileinput({
    language: 'zh', //设置语言
    enctype: 'multipart/form-data',
    showUpload: false, //是否显示上传按钮
    showCaption: false,//是否显示标题
    browseClass: "btn btn-info", //按钮样式
    maxFileCount:1,
    allowedFileExtensions:['zip'],
    msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
});

